import React, {useRef, useState, Fragment} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import {TableListItem} from './data.d';

import {
  queryPageGroupList,
  addGroup,
  updateGroup,
  groupDetail,
  removeGroup,
  queryAuthList
} from "./service";
import moment from 'moment';
import {Divider, Button, message, Tooltip, TreeSelect, Tree} from "antd";
import CreateForm from "./components/CreateForm";
import UpdateForm from "./components/UpdateForm";
import {DeleteOutlined, FormOutlined, PlusOutlined} from "@ant-design/icons/lib";
import {formPropsLayout} from "@/utils/tableUtils";

const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  const res = await updateGroup(fields);
  hide();
  if (res.code == 10000) {
    message.success('更新成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false
};


const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  const res = await addGroup(fields);
  hide();
  if (res.code == 10000) {
    message.success('添加成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false;
};

const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');

  const res = await removeGroup({id: id});
  hide();
  if (res.code == 10000) {
    message.success('删除成功，即将刷新');
    return true;
  }
  message.error('删除失败，请重试');
  return false;

};


const init = {id: 0};

const SysRole: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<TableListItem>(init);
  const [groupList, setGroupList] = useState<TableListItem[]>();
  const [authList, setAuthList] = useState<any[]>();
  const [checkedKeys, setCheckedKeys] = useState<String[]>();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '上级',
      dataIndex: 'pid',
      hideInTable: true,
      hideInSearch: true,
      initialValue: stepFormValues.pid,
      formItemProps: {
        rules: [
          {
            message: "上级为必选项！",
            required: true
          }
        ]
      },
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        return <TreeSelect
          style={{width: '100%'}}
          dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
          treeData={groupList}
          placeholder="请选择"
          fieldNames={{label: 'name', value: 'id', children: 'children'}}
        />;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      initialValue: stepFormValues.name,
      formItemProps: {
        rules: [
          {
            message: "名称为必填项！",
            required: true
          }
        ]
      }
    },
    {
      title: '权限',
      dataIndex: 'auths',
      hideInTable: true,
      hideInSearch: true,
      initialValue: stepFormValues.auths,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {

        return <Tree
          checkable
          onCheck={(checkedKeys:any) => setCheckedKeys(checkedKeys)}
          defaultCheckedKeys={stepFormValues.auths || []}
          treeData={authList}
          fieldNames={{title: 'name', key: 'guid', children: 'children'}}
        />
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      hideInForm: true,
      render: (val: any) => moment(val).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
      render: (val: any) => moment(val).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      hideInForm: true,
      render: (text, record) => (
        <Fragment>
          <span>
            <a
              onClick={async () => {
                const groupRes = await groupDetail({id: record.id});
                if (groupRes.code === 10000) {
                  setStepFormValues(groupRes.data);
                }

                const authRes = await queryAuthList({dataType:'group',typeId:record.id})
                if (authRes.code === 10000) {
                  setAuthList(authRes.data);
                }

                handleUpdateModalVisible(true);

              }}
            >
              <Tooltip title="编辑">
             <FormOutlined/>
              </Tooltip>
            </a>
            <Divider type="vertical"/>
          </span>
          <a onClick={async () => {
            let promise: boolean = await handleRemove(record.id);
            if (promise && actionRef.current) actionRef.current.reload()
          }}>
            <Tooltip title="删除">
              <DeleteOutlined/>
            </Tooltip>
          </a>
        </Fragment>
      ),
    },
  ];


  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="用户组列表"
        actionRef={actionRef}
        toolBarRender={() => [
          <Button type="primary" onClick={async () => {
            const authRes = await queryAuthList()
            if (authRes.code === 10000) {
              setAuthList(authRes.data);
            }
            handleModalVisible(true);
          }}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        dateFormatter="string"
        rowKey='id'
        request={(params) => queryPageGroupList({...params}).then(res => {
          const result = {data: [], success: false};

          if (res.code === 10000) {
            result.success = true;
            result.data = res.data ?? [];
            setGroupList([{name: '主目录', id: 0, children: result.data}])
          }
          return result;
        })}
        pagination={false}
        columns={columns}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value:any) => {
            value.auths = checkedKeys ?? [];
            const success = await handleAdd({...value});
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey={(record, index) => `complete${index}`}
          type="form"
          form={formPropsLayout}
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length && (
        <UpdateForm
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues(init);
          }}
          updateModalVisible={updateModalVisible}
        >
          <ProTable<TableListItem, TableListItem>
            onSubmit={async (value:any) => {
              value.id = stepFormValues.id;
              value.auths = checkedKeys ?? [];
              const success = await handleUpdate({...value});
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues(init);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey={(record, index) => `complete${index}`}
            type="form"
            form={formPropsLayout}
            columns={columns}
            rowSelection={{}}
          />
        </UpdateForm>
      )}
    </PageContainer>
  );
};

export default SysRole;
